using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
//IPointerDownHandler模拟按下
//IPointerClickHandler模拟点击（按下到抬起）
public class UI_TreeNode : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler
{
    private UI uI;
    private RectTransform rect;
    private UI_SkillTree skillTree;
    private UI_TreeConnectionHandler connectHandler;

    [Header("Unlock Details")]
    public UI_TreeNode[] neededNodes;
    public UI_TreeNode[] conflictNodes;
    public bool isUnlocked;
    public bool isLocked;


    [Header("Skill Details")]
    public Skill_DataSO skillData;
    [SerializeField] private string skillName;
    [SerializeField] private Image skillIcon;
    [SerializeField] private int skillCost;
    [TextArea]
    [SerializeField] private string description;
    [SerializeField] private string lockedColorHex = "#9F9797";
    private Color lastColor;

    // 在编辑器中验证和处理属性变更
    private void OnValidate()
    {
        if (skillData == null)
            return;
        skillName = skillData.displayName;
        description = skillData.descrpition;
        gameObject.name = "UI_TreeNode - " + skillData.displayName;
        skillCost = skillData.cost;
        skillIcon.sprite = skillData.icon;
        UpdateIconColor(Color.white);
    }
    private void Start()
    {
        GetNeededComponent();
    }
    private void GetNeededComponent()
    {
        uI = GetComponentInParent<UI>();
        rect = GetComponent<RectTransform>();
        skillTree = GetComponentInParent<UI_SkillTree>(true);
        connectHandler = GetComponent<UI_TreeConnectionHandler>();
    }
    public void SetTreeNode()
    {
        UpdateIconColor(GetColorByHex(lockedColorHex));
        UpdateDefaultSkillUnLock();
    }
    private void UpdateDefaultSkillUnLock()
    {
        GetNeededComponent();
        if (skillData.unlockByDefault && CanBeUnlocked())
            Unlock();
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        if (CanBeUnlocked())
            Unlock();
        else if (isLocked)
            uI.skillToolTip.StartTextBlinkEffectCo();
    }
    private void OnDisable()
    {
        if (isLocked)
            UpdateIconColor(GetColorByHex(lockedColorHex));

        if (isUnlocked)
            UpdateIconColor(Color.white);
    }
    public void OnPointerEnter(PointerEventData eventData)
    {
        uI.skillToolTip.ShowToolTip(true, rect, this);
        if (isUnlocked || isLocked)
            return;
        ToggleNodeHighLight(true);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        uI.skillToolTip.ShowToolTip(false, rect); 
        uI.skillToolTip.StopLockedSkillEffect();
        if (isUnlocked || isLocked)
            return;
        ToggleNodeHighLight(false);
    }
    private void ToggleNodeHighLight(bool highLight)
    {
        Color highLightColor = Color.white * .9f; highLightColor.a = 1f;
        Color colorToAppay = highLight ? highLightColor : lastColor;
        UpdateIconColor(colorToAppay);
    }
    public void Unlock()
    {
        if (isUnlocked)
            return;
        //设置当前节点的解锁状态
        isUnlocked = true;
        //更新消耗
        skillTree.RemoveSkillPoints(skillCost);
        //更新解锁颜色
        UpdateIconColor(Color.white);
        //如果解锁了当前节点，则锁定当前节点的所有冲突节点
        LockConflictNodes();
        connectHandler.UnlockConnectionImageColor(true);
        //设置对应节点属性
        skillTree.playerSkillManager.GetSkillByType(skillData.skillType).SetSkillUpgrade(skillData);
    }

    public void UnlockInLoadData()
    {
        if (isUnlocked)
            return;
        //设置当前节点的解锁状态
        isUnlocked = true;

        //更新解锁颜色
        UpdateIconColor(Color.white);

        //如果解锁了当前节点，则锁定当前节点的所有冲突节点
        LockConflictNodes();

        connectHandler.UnlockConnectionImageColor(true);
    }
    //锁定所有冲突节点
    private void LockConflictNodes()
    {

        foreach (var conflictNode in conflictNodes)
        {
            conflictNode.isLocked = true;
            conflictNode.LockChildNodes();
        }
    }
    
    public void LockChildNodes()
    {
        isLocked = true;
        //遍历每个冲突的子节点然后获取UI_TreeConnectionHandler组件，
        //防止子节点在执行GetNeededComponent()前就执行锁定
        connectHandler = GetComponent<UI_TreeConnectionHandler>();

        foreach (var node in connectHandler.GetAllChildNodes())
            node.LockChildNodes();
    }
    
    //判断是否能够解锁
    private bool CanBeUnlocked()
    {
        //如果自身已经解锁或者自身以因为冲突被锁定
        if (isUnlocked || isLocked)
            return false;
        //如果当前花费品小于技能所需花费
        if (skillTree.EnoughSkillPoints(skillCost) == false)
            return false;
        //如果解锁当前节点所需的节点（父节点）有未解锁的节点
        foreach (var neededNode in neededNodes)
        {
            if (neededNode.isUnlocked == false)
                return false;
        }
        //如果当前节点的冲突节点有已经解锁的
        foreach (var conflictNode in conflictNodes)
        {
            if (conflictNode.isUnlocked)
                return false;
        }
        return true;
    }
    public void Refund()
    {
        if (isUnlocked == false || skillData.unlockByDefault)
            return;

        isLocked = false;
        isUnlocked = false;

        UpdateIconColor(GetColorByHex(lockedColorHex));

        skillTree.AddSkillPoints(skillCost);
        connectHandler.UnlockConnectionImageColor(false);
        
        //设置对应节点属性
        skillTree.playerSkillManager.GetSkillByType(skillData.skillType).SetSkillUpgrade(skillData, true);
    }
    //更新图片颜色
    private void UpdateIconColor(Color color)
    {
        if (skillIcon == null)
            return;
        //记录颜色
        lastColor = skillIcon.color;
        skillIcon.color = color;
    }
    //通过二进制转化成相应颜色
    private Color GetColorByHex(string hexNumber)
    {
        ColorUtility.TryParseHtmlString(hexNumber, out Color color);
        return color;
    }
}
